package com.wlcb.jpower.chat.controller.wx.mp;

import com.wlcb.jpower.chat.service.wx.mp.TemplateMsgService;
import com.wlcb.jpower.module.base.enums.JpowerError;
import com.wlcb.jpower.module.base.exception.JpowerAssert;
import com.wlcb.jpower.module.base.vo.ResponseData;
import com.wlcb.jpower.module.common.controller.BaseController;
import com.wlcb.jpower.module.common.utils.ReturnJsonUtil;
import com.wlcb.jpower.utils.WxMpInstance;
import com.wlcb.jpower.wx.mp.template.WxTemplateRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: liwenfei
 * @version: v1.0
 * @time: 2021/3/2 14:18
 * @desc: 模板消息接口实现
 */
@Api(tags = "模板消息")
@RestController
@RequestMapping("template")
@RequiredArgsConstructor
public class TemplateMsgController extends BaseController {

    private final TemplateMsgService templateMsgService;

    @ApiOperation("发送模板")
    @PostMapping("send")
    public ResponseData send(@RequestBody WxTemplateRequest request,
                             @ApiParam(value = "发送失败是否发送钉钉通知",defaultValue = "false") @RequestParam(defaultValue = "false") Boolean exSend) {
        JpowerAssert.notEmpty(request.getAppId(), JpowerError.Arg,"公众号ID不可为空");

        int i = templateMsgService.templateSend(request, exSend);
        if (request.getToUsers().size() == i) {
            return ReturnJsonUtil.ok("发送成功");
        }
        return ReturnJsonUtil.fail("发送失败", "发送总数：" + request.getToUsers().size() + "\n 成功数量：" + i);
    }

    @ApiOperation("获取模板列表")
    @GetMapping("list")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<List<WxMpTemplate>> getTemplates(@ApiParam("公众号ID") String appId) {
        JpowerAssert.notEmpty(appId, JpowerError.Arg,"公众号ID不可为空");

        WxMpService wxMpService = WxMpInstance.getWxMp().switchoverTo(appId);
        List<WxMpTemplate> templates = wxMpService.getTemplateMsgService().getAllPrivateTemplate();
        return ReturnJsonUtil.ok("操作成功", templates);
    }

    @ApiOperation("删除模板")
    @DeleteMapping("/delete")
    @SneakyThrows(WxErrorException.class)
    public ResponseData delete(@ApiParam("公众号ID") String appId,@ApiParam("模板ID") String templateId) {
        JpowerAssert.notEmpty(appId, JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notEmpty(templateId, JpowerError.Arg,"模板ID不可为空");

        WxMpService wxMpService = WxMpInstance.getWxMp().switchoverTo(appId);
        return ReturnJsonUtil.status(wxMpService.getTemplateMsgService().delPrivateTemplate(templateId));
    }
}
